package net.app.zoneland.oauth.config;

import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.io.ClassPathResource;
import org.springframework.security.oauth2.provider.token.TokenStore;
import org.springframework.security.oauth2.provider.token.store.JwtAccessTokenConverter;
import org.springframework.security.oauth2.provider.token.store.JwtTokenStore;
import org.springframework.security.oauth2.provider.token.store.KeyStoreKeyFactory;
import java.security.KeyPair;

/**
 * @Description
 * @Author cjb
 * @CreateTime 2020/12/27 19:32
 * @Version: 1.0
 */
@Configuration
public class TokenStoreConfig {

    @Bean
    public TokenStore tokenStore(){
        return new JwtTokenStore(jwtAccessTokenConverter());
    }

    @Bean
    public JwtAccessTokenConverter jwtAccessTokenConverter(){
        JwtAccessTokenConverter jwtAccessTokenConverter=new JwtAccessTokenConverter();
        jwtAccessTokenConverter.setKeyPair(keyPair()); // 设置非对称加密秘钥
        return jwtAccessTokenConverter;
    }

    /**
     * 从classpath路径下获取秘钥对(公钥+私钥)
     * @return
     */
    @Bean
    public KeyPair keyPair(){
        ClassPathResource resource=new ClassPathResource("oauth2.jks");
        KeyStoreKeyFactory factory=new KeyStoreKeyFactory(resource,"oauth2".toCharArray());
        KeyPair keyPair = factory.getKeyPair("oauth2", "oauth2".toCharArray());
        return keyPair;
    }

}
